package com.noble.meether.chat.ui.agora.act.voice;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.bean.my.GiftsList;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.baseui.custom.CountDownTextView;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.library.image.ImageLoader;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.utils.BitmapUtil;
import com.noble.library.utils.NoDoubleClickListener;
import com.noble.library.utils.UIUtil;
import com.noble.library.view.live.gift.GiftControl;
import com.noble.library.view.live.gift.widget.GiftModel;
import com.noble.meether.R;
import com.noble.meether.chat.ui.agora.act.base.RtcBaseActivity;
import com.noble.meether.chat.ui.agora.act.mail.RtcMsgAdapter;
import com.noble.meether.chat.ui.agora.act.video.ChatFootPanel;
import com.noble.meether.chat.ui.agora.dialog.listener.GiftSendListener;
import com.noble.meether.chat.ui.agora.model.AgoraConstant;
import com.noble.meether.chat.ui.agora.util.RtcJointChannel;
import com.noble.meether.chat.ui.agora.util.RtcSubUtil;
import com.noble.meether.chat.ui.agora.util.RtcTimerUtil;
import com.noble.meether.chat.ui.agora.util.RtcUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 语音接通界面
 */
public class RtcVoiceActivity extends RtcBaseActivity implements PObserver, RequestComplete, GiftSendListener {
    private RelativeLayout rootView;
    private LinearLayout msgTipsLayout;      // 钻石不足提示消息
    private LinearLayout functionPanel;      // 底部功能按钮
    private CountDownTextView tipsCountDown; // 钻石不足提示倒计时
    private ImageView imgBg, imgHead;
    private TextView tv_name;

    private ChatFootPanel footPanel;
    private int lastHeight = 0;
    private ImageView btnSwitchMicro;        // 切换话筒

    private UserDetail userDetail;          // 自己资料
    private UserDetail otherInfo;          // 他人资料
    private RecyclerView recyclerView;      // 消息列表展示
    private RtcMsgAdapter msgAdapter;
    private List<String> msgList;

    private GiftControl giftControl;        // 礼物特效
    private GiftModel giftModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (synthHandle()) {
            rootView = (RelativeLayout) getLayoutInflater().inflate(R.layout.p1_chat_voice, null);
            setContentView(rootView);
            initView();
            addGlobalListener();
            RtcJointChannel.getInstance().reqUserInfo(this);
        }
    }

    private void addGlobalListener() {
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            if (isFinishing()) return;
            Rect r = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
            int screenHeight = getWindow().getDecorView().getRootView().getHeight();
            int heightDifference = screenHeight - r.bottom;
            if (heightDifference == 0 && lastHeight > 0) {
                footPanel.moveInputPanel(0);
            } else if (heightDifference > 0) {
                footPanel.moveInputPanel(-heightDifference);
            }
            lastHeight = heightDifference;
        });
    }

    private void initView() {
        userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        functionPanel = findViewById(R.id.chat_faction_panel);
        imgBg = findViewById(R.id.iv_bg);
        Bitmap bitmap = BitmapUtil.getDecodeBitmap(this, R.drawable.sp_bk, 320, 480);
        UIUtil.setBackground(imgBg, new BitmapDrawable(null, bitmap));
        imgHead = findViewById(R.id.iv_head);
        tv_name = findViewById(R.id.tv_name);

        btnSwitchMicro = findViewById(R.id.voice_switch);
        btnSwitchMicro.setImageResource(RtcJointChannel.getInstance().getSwitchMicro() ?
                R.drawable.p1_btn_switch_mianti2 : R.drawable.p1_btn_switch_mianti1);
        btnSwitchMicro.setOnClickListener(listener);

        // 底部功能按键
        footPanel = new ChatFootPanel(this);
        footPanel.beautyHidden();
        functionPanel.addView(footPanel.getContentView());

        // 男性显示余额计时
        if (userDetail.isMan()) {
            initCountDownTimer();
        }

        Chronometer chatTime = findViewById(R.id.ch_count_time);
        chatTime.setBase(SystemClock.elapsedRealtime() - config().millisPass);
        RtcTimerUtil.getInstance().addTimer(chatTime);
        chatTime.start();

        initGiftView();
        initMsgList();
        findViewById(R.id.iv_shrink_narrow).setOnClickListener(listener);
        ModuleMgr.getRtcEnginMgr().joinChannel(this);
    }

    /**
     * 音视频双方同步操作
     */
    private boolean synthHandle() {
        // 已经收到对方挂断消息
        if (RtcUtil.getInstance().isReceiveReject()) {
            RtcUtil.getInstance().resetReceiveReject();
            finish();
            return false;
        }

        // 等待界面已经点挂断，但是还收到接收消息
        if (RtcUtil.getInstance().isHandleUp()) {
            RtcUtil.getInstance().resetHandleUp();
            finish();
            return false;
        }
        MsgMgr.getInstance().attach(this);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (RtcUtil.getInstance().isHangUp()) {  // 对方用户快速挂断
            finish();
        }
    }

    /**
     * 消息列表展示
     */
    private void initMsgList() {
        recyclerView = findViewById(R.id.list_msg);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        msgAdapter = new RtcMsgAdapter();
        msgList = Collections.synchronizedList(new ArrayList<String>());
        recyclerView.setAdapter(msgAdapter);
        msgAdapter.setList(msgList);
    }

    private void initCountDownTimer() {
        msgTipsLayout = findViewById(R.id.msg_tips);
        tipsCountDown = findViewById(R.id.tv_countDown);
        RtcTimerUtil.getInstance().addTimer(tipsCountDown);
        TextView tipsTxt = findViewById(R.id.time_left_tips);

        // 女号都是邀请流程，扣费方全部为男方扣费
        if (!userDetail.isMan())
            tipsTxt.setText(getString(R.string.chat_tips_other_no_diamond));

        if (config().millisLeft > 0 && config().millisLeft <= AgoraConstant.CHAT_COST_PROMPT) {
            msgTipsLayout.setVisibility(View.VISIBLE);
            tipsCountDown.setCountDownTimes(config().millisLeft * 1000);
            tipsCountDown.start();
        }
    }

    // ------------------------------ 礼物收发 ------------------------------------

    // 礼物动画容器
    private void initGiftView() {
        LinearLayout giftParent = findViewById(R.id.ll_gift_parent);
        giftModel = new GiftModel();
        giftControl = new GiftControl(this);
        giftControl.setGiftLayout(giftParent, 3)
                .setDisplayMode(GiftControl.FROM_BOTTOM_TO_TOP);

        // 设置礼物消息接收监听
        if (!userDetail.isMan())
            RtcUtil.getInstance().setGiftSendListener(this);
    }

    @Override
    public void sendGiftSuccess(GiftsList.GiftInfo info) {
        giftSend(info);
    }

    private void giftSend(GiftsList.GiftInfo info) {
        if (info == null) return;
        giftModel.setGiftId(String.valueOf(info.getId())).setGiftName(info.getName()).setGiftCount(info.getNum()).setGiftPic(info.getPic())
                .setSendUserName(otherInfo.getNickname()).setSendUserPic(otherInfo.getAvatar())
                .setJumpCombo(info.getNum())
                .setSendGiftTime(System.currentTimeMillis())
                .setCurrentStart(true);
        giftControl.loadGift(giftModel);
    }


    @Override
    public void onRequestComplete(HttpResponse response) {
        if (response.getUrlParam() == UrlParam.reqMyInfo) {
            if (!response.isOk()) return;
            otherInfo = (UserDetail) response.getBaseData();
            tv_name.setText(otherInfo.getNickname());
            ImageLoader.loadBlur(this, otherInfo.getAvatar(), imgBg, 8, R.drawable.sp_bk);
            ImageLoader.loadRoundAvatar(this, otherInfo.getAvatar(), imgHead);
        }
    }

    /**
     * 点击事件
     */
    private NoDoubleClickListener listener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.voice_switch:
                    RtcJointChannel.getInstance().switchMicro();
                    break;
                case R.id.iv_shrink_narrow: // 最小化
                    if (checkOverLaysPermission())
                        ModuleMgr.getRtcEnginMgr().startRtcFloatService();
                    break;
            }
        }
    };

    /**
     * 通话状态消息：由主Apk传递状态值
     */
    @Override
    public void onMessage(String key, Object value) {
        try {
            switch (key) {
                case MsgType.MT_Rtc_Chat_Status:
                    Map<String, Object> data = (Map<String, Object>) value;
                    switch ((int) data.get("type")) {
                        case AgoraConstant.RTC_MSG_REJECT:     // 拒絕加入
                        case AgoraConstant.RTC_MSG_HANGON:     // 挂断
                            PToast.showShort(getString(R.string.chat_tips_hangup));
                            finish();
                            break;
                    }
                    break;

                case MsgType.MT_Rtc_Chat_Connect_Suc:
                    LoadingDialog.closeLoadingDialog();
                    break;

                case MsgType.MT_Rtc_Chat_Close_Msg:
                    finish();
                    break;

                case MsgType.MT_Rtc_Chat_Timer_Msg:
                    if (!userDetail.isMan()) return;
                    if ((int) value == AgoraConstant.TIMER_LAST_TIPS) {
                        msgTipsLayout.setVisibility(View.VISIBLE);
                        tipsCountDown.setCountDownTimes(config().millisLeft * 1000);
                        tipsCountDown.start();
                    }
                    break;
                case MsgType.MT_MyInfo_Change:          // 个人资料变化，目前只有充值成功后接收此消息，取消余额倒计时
                    if (!userDetail.isMan()) return;
                    userDetail = ModuleMgr.getCenterMgr().getMyInfo();
                    RtcTimerUtil.getInstance().stopStatisTipsTime(); // 停止余额倒计时
                    msgTipsLayout.setVisibility(View.GONE);
                    tipsCountDown.cancel();
                    RtcSubUtil.getInstance().startVideoChatTime();  // 接通后开启轮询付费信息
                    break;
                case MsgType.MT_Rtc_Chat_Switch_Micro:
                    refreshSwitchMicro((Boolean) value);
                    break;

                case MsgType.MT_Msg_AvChat_MY:  // 接收消息
                    refreshMsgList(userDetail.getNickname(), value);
                    break;

                case MsgType.MT_Msg_AvChat_Other:
                    if (otherInfo == null) otherInfo = new UserDetail();
                    refreshMsgList(otherInfo.getNickname(), value);
                    break;
            }
        } catch (Exception e) {
        }
    }

    public void refreshSwitchMicro(boolean value) {
        btnSwitchMicro.setImageResource(value ? R.drawable.p1_btn_switch_mianti2 :
                R.drawable.p1_btn_switch_mianti1);
    }

    private void refreshMsgList(String name, Object value) {
        try {
            String msg = (String) value;
            if (TextUtils.isEmpty(msg)) return;
            msgList.add(name + "：" + msg);
            msgAdapter.notifyItemInserted(msgList.size() - 1);
            recyclerView.smoothScrollToPosition(msgList.size() - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void finish() {
        super.finish();
        LoadingDialog.closeLoadingDialog();
        MsgMgr.getInstance().detach(this);
        RtcUtil.getInstance().setGiftSendListener(null);
        RtcUtil.getInstance().resetSynchStatus();   // 重置挂断状态
        // 处于悬浮窗， 则只需释放本地Timer计时
        if (RtcJointChannel.getInstance().getFloatStatus()) {
            ModuleMgr.getRtcEnginMgr().releaseLocalTimer();
            return;
        }
        RtcJointChannel.getInstance().resetSwitchMicro();
        ModuleMgr.getRtcEnginMgr().releaseAll();
        MsgMgr.getInstance().sendMsg(MsgType.MT_Update_MyInfo, null);
    }
}
